/*
 * Written By	: Chang Hyun Park
 * Student ID	: 2007******
 * Major		: Computer Engineering
 * Subject		: Data Communication
 * Filename		: EchoClient.java
 */
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.util.Scanner;


public class EchoClient
{
	/**
	 * @param The values inputted as arguments will be used as the Server's IP address and the Port number.
	 * @throws Exception Exception required when using DatagramSocket
	 * @author Chang Hyun Park
	 */

	public static void main(String[] args) throws Exception
	{
		byte[] sendData = new byte[1024];
		byte[] recvData = new byte[1024];
		
		DatagramSocket clientSocket = new DatagramSocket();
		Scanner keyboard = new Scanner(System.in);	//Scanner Class to get input
		String buffer = new String();

		int serverPort;
			
		InetAddress serverIP, clientIP;
		if(args.length!=0)
		{
			serverIP = InetAddress.getByName(args[0]);	//IP Address
			if(args.length==2)
				serverPort = Integer.parseInt(args[1]);	//Port Number if inserted after IP
			else
				serverPort = 64777;	//Defalut
		}
		else
		{
			serverIP = InetAddress.getByName("127.0.0.1");//localhost
			serverPort = 64777;
		}
		
		
		clientIP = InetAddress.getLocalHost();
		System.out.println("(1)   This Client's IP Address and Port number is as follows : \""+
				clientIP.toString()+":"+clientSocket.getLocalPort()+"\"");
		//Find Client IP and Port number
		
		System.out.println("Sending Packet to ["+serverIP.toString().substring(1)+":"+serverPort+"]");
		//toString().substring(1) to eliminate an extra "/" in the serverIP.toString()
		while(true)
		{
			DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,serverIP,serverPort);
			try{
				Receive r1 = new Receive(clientSocket, recvData);//Create Receiving Thread
				
				
				System.out.print("-->");
	
				buffer = new String(keyboard.nextLine());
				sendPacket.setData(buffer.getBytes());	//Pack string into Datagram Packet
				clientSocket.send(sendPacket);	//Send to Server
				System.out.println("Client Sends = \""+buffer+"\"");
				clientSocket.setSoTimeout(1000);
				r1.start();//Start the thread
				r1.join();//Wait for thread to finish before going on to next while loop!
			}
			catch(SocketTimeoutException e)
			{
				System.out.println(e+"Resending Packet");
				clientSocket.send(sendPacket);
			}

			
		}
	}

}
